import React, { useState, useEffect, Key, useCallback, useMemo } from 'react';
import { Modal, Tree, Row, Col, Input, Table, Tag, message } from 'antd';
import { getWebSiteIDList, getIndexList, IIndexData } from '../service';
import { getCookie, InbizIcon } from '@inbiz/utils';
import { IConfig } from './configDetail';
import { getDefaultConfig } from './LibraryConfig';
import './addIndexLibrary.less';
import Pagination from '@inbiz/basic/Pagination';
import { getMessage, TextWidget } from '@inbiz/react';
import { useUpdateEffect } from 'ahooks';
export interface IAddIndexLibraryProps {
  appId: string;
  visible: boolean;
  onSave: (list: (IIndexData & { configs: IConfig[] })[]) => void;
  select?: (IIndexData & { configs?: IConfig[] })[]; // 初始选中的key
  onCancel: () => void;
}

interface DataNode {
  title: string;
  key: string;
  isLeaf?: boolean;
  children?: DataNode[];
}

let initTreeData: DataNode[] = [];

export const AddIndexLibrary: React.FC<IAddIndexLibraryProps> = (props) => {
  const { visible, onSave, onCancel, select } = props;
  const [treeData, $treeData] = useState(initTreeData);
  const [selectedRowKeys, $selectedRowKeys] = useState<Key[]>(
    select?.map((item) => item.IndexName) || [],
  ); // 当前table选中的key
  const [selectedAllIndex, $selectedAllIndex] = useState(
    (select || []) as (IIndexData & { configs: IConfig[] })[],
  ); // 切换索引库，所有table选中key
  const [tableData, $tableData] = useState<{
    Items: IIndexData[];
    Total: number;
  }>({
    Items: [],
    Total: 0,
  }); // 索引库表格数据
  const [currentParams, $currentParams] = useState(() => ({
    WebSiteID: props.appId, // 应用id
    isOtherSite: false, // 是否是其他应用
    pageIndex: 1,
    pageSize: 20,
    token: getCookie('token')!,
    KeyWord: '', // 关键字
  })); // 获取当前应用索引库的搜索参数

  const [treeSelectedKeys, $treeSelectedKeys] = useState<string[]>([]);

  useEffect(() => {
    if (!visible) {
      return;
    }
    $currentParams({
      ...currentParams,
      WebSiteID: (treeSelectedKeys[0] === '_other' ? props.appId : treeSelectedKeys[0]) as string,
      isOtherSite: treeSelectedKeys[0] === '_other',
    });
    $selectedRowKeys(select?.map((item) => item.IndexName) || []);
    $selectedAllIndex((select || []) as typeof selectedAllIndex);
  }, [props.appId, treeSelectedKeys, visible]);

  // 	点击树节点触发
  const onSelect = (selectedKeys: Key[]) => {
    if (!selectedKeys.length) {
      return;
    }
    $treeSelectedKeys(selectedKeys as string[]);
    $selectedRowKeys(selectedAllIndex.map((item) => item.IndexName));
  };

  // 获取应用列表数据
  useEffect(() => {
    if (initTreeData?.length) {
      $treeSelectedKeys([initTreeData[0].key]);
      return;
    }
    // 获取应用列表数据
    getWebSiteIDList(props.appId).then((res) => {
      const list: { key: string; title: string }[] = [];
      res?.forEach((item) => {
        if (item.WebSiteID != props.appId) {
          list.push({
            key: item.WebSiteID,
            title: item.DisplayName,
          });
        }
      });
      const data = [
        {
          key: props.appId,
          title: getMessage('SearchResultEngine.currentApplication'),
          isOtherSite: true,
          className: 'currentApplication',
        },
        {
          key: '_other',
          title: getMessage('SearchResultEngine.otherApplication'),
          children: list,
        },
      ];
      initTreeData = data;
      $treeSelectedKeys([data[0].key]);
      $treeData(data);
    });
  }, []);

  // 获取当前应用下的索引库
  useUpdateEffect(() => {
    getIndexList(currentParams).then((res) => {
      if (res.Code == 0) {
        $tableData(res.Data);
      }
    });
  }, [currentParams]);
  // 添加索引库确定按钮事件
  const handleOk = () => {
    if (!selectedAllIndex.length) {
      message.warn(getMessage('SearchResultEngine.pleaseSelectIndexLibrary'));
      return;
    }
    $treeSelectedKeys([props.appId]);
    onSave &&
      onSave(
        selectedAllIndex.map((item) => {
          if (item.configs) {
            return item;
          } else {
            return {
              ...item,
              configs: getDefaultConfig(item.IndexName),
            };
          }
        }),
      );
  };

  // 添加索引库取消按钮事件
  const onCancelClick = () => {
    // 清空选择的数据
    $selectedRowKeys([]);
    $selectedAllIndex([]);
    $treeSelectedKeys([props.appId]);
    onCancel && onCancel();
  };

  // 表格行是否可选择，配置项
  const rowSelection = {
    selectedRowKeys,
    onSelectAll: (selected: any, selectedRows: any, changeRows: any[]) => {
      const currentIndex = [...selectedAllIndex];
      if (selected) {
        // 全选
        changeRows.map((item) => {
          currentIndex.push(item);
        });
        $selectedRowKeys((old) => {
          return Array.from(new Set([...old, ...(changeRows.map((item) => item.IndexName) || [])]));
        });
        $selectedAllIndex(currentIndex);
      } else {
        // 全不选
        const changeList = changeRows.map((item) => item.IndexName);
        changeList.forEach((item) => {
          currentIndex.map((list: { IndexName: any }, index: any) => {
            if (item == list.IndexName) {
              currentIndex.splice(index, 1);
            }
          });
        });
        $selectedRowKeys((old) => {
          return old.filter((item) => !changeList.includes(item));
        });

        $selectedAllIndex(currentIndex);
      }
    },
    onSelect: (record: { IndexName: string }, selected: boolean) => {
      const currentIndex = [...selectedAllIndex];
      if (selected) {
        currentIndex.push(record as any);
        $selectedRowKeys((keys) => [...keys, record.IndexName]);
        $selectedAllIndex(currentIndex);
      } else {
        currentIndex.forEach((element: { IndexName: any }, index: any) => {
          if (element.IndexName == record.IndexName) {
            currentIndex.splice(index, 1);
          }
        });
        $selectedRowKeys((keys) => keys.filter((item) => item != record.IndexName));
        $selectedAllIndex(currentIndex);
      }
    },
  };

  // 表格列的配置描述
  const columns = useMemo(() => {
    return [
      {
        title: getMessage('SearchResultEngine.indexLibraryName'),
        dataIndex: 'IndexName',
      },
    ];
  }, []);

  // 点击搜索图标、清除图标，或按下回车键时的回调
  const onSearch = (e: { target: { value: any } }) => {
    $currentParams({
      ...currentParams,
      KeyWord: e.target.value,
    });
  };
  // 分页修改
  const handlePaginationChange = useCallback(({ current: pageIndex, pageSize }) => {
    $currentParams((params) => ({
      ...params,
      pageIndex,
      pageSize,
    }));
  }, []);

  // 选中列表
  const [showSelectList, $showSelectList] = useState(false);

  const selectList = useMemo(() => {
    return selectedAllIndex.filter((item) => item.IndexType !== -1);
  }, [selectedAllIndex]);

  const handleDelete = useCallback((IndexName: string) => {
    $selectedRowKeys((keys) => keys.filter((key) => key !== IndexName));
    $selectedAllIndex((list) => list.filter((item) => item.IndexName !== IndexName));
  }, []);

  const handelClickRow = useCallback(
    (record: { IndexName: any }) => {
      return {
        onClick: () => {
          rowSelection.onSelect(record, !selectedRowKeys.find((item) => item === record.IndexName));
        },
      };
    },
    [selectedRowKeys, selectedAllIndex],
  );
  return (
    <div>
      <Modal
        title={getMessage('SearchResultEngine.addIndexLibrary')}
        width={800}
        visible={visible}
        onOk={handleOk}
        onCancel={onCancelClick}
        cancelText={getMessage('SearchResultEngine.cancel')}
        okText={getMessage('SearchResultEngine.determine')}
        destroyOnClose
        zIndex={10}
        bodyStyle={{ height: 488 }}
      >
        <div className="addIndexLibrary-box">
          <Row className="addIndexLibrary-content">
            <Col span={6}>
              <Tree
                treeData={treeData}
                onSelect={onSelect}
                selectedKeys={treeSelectedKeys}
                height={475 - (showSelectList ? 113 : 0)}
                blockNode
              />
            </Col>
            <Col span={18}>
              <Input
                placeholder={getMessage('SearchResultEngine.pleaseEnterIndexLibraryName')}
                onChange={onSearch}
                suffix={<InbizIcon type={'icon-ic-sousuo'} style={{ color: '#ddd' }} />}
              />
              <Table
                rowKey={(record) => record.IndexName}
                scroll={{ y: 'auto' }}
                style={{ '--border-height': 350 - (showSelectList ? 113 : 0) + 'px' }}
                size="small"
                rowSelection={rowSelection}
                columns={columns}
                pagination={false}
                dataSource={tableData.Items}
                className={
                  !tableData.Items?.length ? 'addIndexLibraryTable noData' : 'addIndexLibraryTable'
                }
                onRow={handelClickRow}
              />
              <Pagination
                total={tableData.Total}
                current={currentParams.pageIndex}
                pageSize={currentParams.pageSize}
                onChange={handlePaginationChange}
                options={[10, 20, 30, 40, 50]}
              />
            </Col>
          </Row>
          <div className="select-list" style={{ display: showSelectList ? 'block' : 'none' }}>
            {selectList.map((item) => {
              return (
                <Tag
                  key={item.IndexName}
                  closable
                  closeIcon={<InbizIcon type="icon-ic-clear" />}
                  onClose={() => handleDelete(item.IndexName)}
                >
                  {item.IndexName}
                </Tag>
              );
            })}
          </div>
          <div className="selectNumber">
            <TextWidget>SearchResultEngine.numberOfSelected</TextWidget>:
            <span className="number">{selectList?.length || 0}</span>
            <InbizIcon
              type="icon-ic-arrow-down-bold"
              style={{ transform: `rotate(${showSelectList ? 180 : 0}deg)` }}
              onClick={() => $showSelectList(!showSelectList)}
            />
          </div>
        </div>
      </Modal>
    </div>
  );
};
